﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using StockUtil;

namespace StockLib.UserData
{
    public class BlockCustomFileLoader
    {
        public virtual void Load()
        {
            FileInfo fi = new FileInfo(StockUserData.Instance.GetFileName(UserDataType.Block));
            if (!fi.Exists)
                return;

            FileStream fs = null;
            StreamReader sr = null;

            try
            {
                fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                sr = new StreamReader(fs, Encoding.Default);

                StockBlockGroupCustom.Instance.Clear();

                string blockName = string.Empty;
                StockBlock domain = null;
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    if (!string.IsNullOrEmpty(line))
                    {
                        line = line.Trim();
                    }
                    if (string.IsNullOrEmpty(line))
                        continue;

                    if (line.StartsWith("--"))
                    {
                        if (domain != null)
                        {
                            StockBlockGroupCustom.Instance.Add(domain.BlockId, domain);
                        }

                        blockName = string.Empty;
                        continue;
                    }

                    if (string.IsNullOrEmpty(blockName))
                    {
                        blockName = line;

                        domain = new StockBlock();
                        domain.Name = blockName;
                        domain.ShortName = StringHelper.GetPinYin(domain.Name);
                        domain.GroupName = "板块";
                        domain.StockNumber = 0;
                    }
                    else
                    {
                        if (domain != null)
                        {
                            if (StockContainer.Instance.ContainsKey(line) && !domain.ContainsKey(line))
                            {
                                domain.Add(line, StockContainer.Instance[line]);
                                domain.StockNumber = domain.Count;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }

                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
    }
}
